package com.mjh.controller;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mjh.exception.FileWriterFilaException;
import com.mjh.mapper.FileEntiyMapper;
import com.mjh.pojo.FileEntiy;
import com.mjh.pojo.Sbcl;
import com.mjh.service.impl.FileEntiyServiceImpl;
import com.mjh.service.impl.SbclServiceImpl;
import com.mjh.util.JwtUtil;
import io.minio.*;
import io.minio.errors.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 附件与文件表 前端控制器
 *
 *
 * @author MJH
 * @since 2021-12-03
 */
@RestController
public class FileEntiyController {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SbclServiceImpl sbclService;

    @Value("${minio.bucket}")
    private String bucket;

    @Autowired
    private FileEntiyMapper fileEntiyMapper;

    @Value("${minio.host}")
    private String minioHost;





    /**
     * 上传个人申报材料
     *
     * @param id   材料编号
     * @param file 材料文件
     * @param clbh 文件所属材料
     * @throws Exception
     */
    @PostMapping("/materialsUpload/{materialsid}")
    public synchronized void materialsUpload(@PathVariable("materialsid") String id, MultipartFile file, Integer clbh) throws Exception {


        Integer userId = (Integer) JwtUtil.getPayload(request, "userId");

        //个人申报材料存储路径 申报活动编号 用户编号
        String prefix = "GRSBCL/" + id + "/" + userId + "/";

        String originalFilename = file.getOriginalFilename();
        //截取文件后缀
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));

        //设置文件名称
        String fileName = IdUtil.fastSimpleUUID() + fileType;
        //将材料文件上传至Minio
        minioClient.putObject(PutObjectArgs.builder()
                .object(prefix + fileName)
                .bucket(bucket).stream(
                        file.getInputStream(), file.getInputStream().available(), -1).build());
        //申报材料实体
        Sbcl sbcl = new Sbcl();
        //封装申报材料实体
        sbcl.setCreateUser(userId);
        sbcl.setFileLink(prefix + fileName);
        sbcl.setClbh(clbh);
        sbclService.save(sbcl);


    }

    /**
     * 文件下载
     *
     * @param path 文件路径
     */

    @RequestMapping("/file/down")
    public void flieDownload(@RequestParam("path") String path,HttpServletResponse response) {

        InputStream in = null;
        OutputStream out = null;
        try {
            //minio下载
            GetObjectResponse objectResponse = minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(path).build());
            in = objectResponse;
            out = response.getOutputStream();
            response.reset();
            response.addHeader("Content-Disposition",
                    " attachment;filename=" + new String(objectResponse.object().getBytes("UTF-8"), "ISO-8859-1"));
             String orgin= request.getHeader("Origin");

            response.addHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
            response.addHeader("'Access-Control-Allow-Credentials","true");
            response.setContentType("application/octet-stream");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) >= 0) {
                out.write(buffer, 0, len);

            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new FileWriterFilaException("文件下载失败");
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }


    /**
     * 获取文件下载列表
     *
     * @param currentPage 当前页
     * @param pageSize    每页数量
     * @param filetype    文件类型   小于零则查询所有
     * @return
     */
    @GetMapping("file/list")
    public ResponseEntity<Object> getFileInfo(@RequestParam(defaultValue = "1") Integer currentPage,
                                              @RequestParam(defaultValue = "10") Integer pageSize, Integer filetype) {

        Page<FileEntiy> page = new Page<>(currentPage, pageSize);
        QueryWrapper<FileEntiy> wrapper = new QueryWrapper<>();
        if (filetype != null && filetype >= 0) {
            wrapper.eq("file_type", filetype);
        }
        Page<FileEntiy> fileInfoList = fileEntiyMapper.selectPage(page, wrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",fileInfoList.getTotal());
        map.put("currentPage",fileInfoList.getCurrent());
        map.put("list",fileInfoList.getRecords());


        return ResponseEntity.ok(map);
    }

    /**
     * 个人照片上传
     * @param file 图片
     * @return  照片链接
     */
    @PostMapping("user/photo")
    public ResponseEntity<String> uploadPhoto(MultipartFile file){
        String fileName="";
        try {
            String originalFilename = file.getOriginalFilename(); //获取文件链接
            String type=originalFilename.substring(originalFilename.lastIndexOf("."));  //截取文件后缀
            fileName=IdUtil.fastSimpleUUID()+type;  //生成新文件名
            minioClient.putObject(PutObjectArgs.builder().object("photo/"+fileName).bucket(bucket).stream(
                    file.getInputStream(), file.getInputStream().available(), -1).build());//上传至minio
        } catch (Exception e) {
            e.printStackTrace();
            throw  new FileWriterFilaException("文件上传失败");
        }

        return ResponseEntity.ok("photo/"+fileName);

    }




}
